package com.gitee.ixtf.rsocket

import io.netty.buffer.ByteBuf
import io.rsocket.Payload
import io.rsocket.metadata.CompositeMetadata
import io.rsocket.metadata.CompositeMetadata.WellKnownMimeTypeEntry
import io.rsocket.metadata.RoutingMetadata
import io.rsocket.metadata.WellKnownMimeType
import io.rsocket.metadata.WellKnownMimeType.*

class RSocketMetadata(payload: Payload) {
  private val metadataStore =
      CompositeMetadata(payload.metadata(), false).associate {
        val entry = WellKnownMimeTypeEntry(it.content, fromString(it.mimeType!!))
        entry.type to entry.content
      }
  private val routeMetadata = RouteMetadata(metadataStore)
  private val messageMetadata = MessageMetadata(metadataStore)
  val route = routeMetadata.route ?: BROKER_ROUTE
  val messageMimetype = messageMetadata.type ?: APPLICATION_JSON
}

private class RouteMetadata(metadataStore: Map<WellKnownMimeType, ByteBuf>) {
  val route = metadataStore[MESSAGE_RSOCKET_ROUTING]?.let { RoutingMetadata(it).first() }
}

private class MessageMetadata(metadataStore: Map<WellKnownMimeType, ByteBuf>) {
  val type = metadataStore[MESSAGE_RSOCKET_MIMETYPE]?.let { fromIdentifier(it.readByte().toInt()) }
}
